package com.mamingchao.concurrent.threads_communication3;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;
import java.util.concurrent.locks.LockSupport;

/**
 * Created by mamingchao on 2020/9/18.
 *
 * 这个是自己写的
 *
 * 实现一个容器，提供add和size两个方法
 * 写两个线程，线程1向容器放10个元素，线程2监控元素个数
 * 当元素个数到5时，线程2给出提示并结束
 */


public class TaobaoInterview {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(5);

        ElementContainer ec = new ElementContainer();

        Thread t1 = new Thread(() -> {
            for (int i=0;i<10;i++) {
                ec.addElement();
                latch.countDown();
                if (latch.getCount() ==0) {
                    System.out.println("Already come to 5");
                    LockSupport.park();
                }
            }
        });

        t1.start();

        TimeUnit.SECONDS.sleep(2);

        System.out.println("Current container size is " + ec.getContainerSize());

    }





    private static class ElementContainer{
        private LongAdder counter = new LongAdder();

        public void addElement(){
            counter.increment();
        }

        public int getContainerSize(){
            return counter.intValue();
        }
    }
}
